package han.util;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import static com.han.http.util.Print.printlnInfo;

/**
 * @fileName: ListTool
 * @author: Han
 * @date: 2018/6/26 13:26
 * @dscription: List工具
 */
public class ListTool<T> {

    public static void main(String... args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        List<List<Integer>> splitList = new ListTool<Integer>().splitListByCount(list, 5);
        for (List<Integer> tempList : splitList) {
            printlnInfo(tempList);
        }
    }

    /**
     * 将list按照指定每个指定数量分开
     *
     * @param list 原始list
     * @param size 分开后每个list的数量
     * @return 分开后的list
     */
    public List<List<T>> splitListBySize(List<T> list, int size) {
        List<List<T>> lists = new LinkedList<>();
        //如果传入list数量小于分开数,直接返回原list
        if (list.size() < size) {
            lists.add(list);
            return lists;
        }
        List<T> tempList = new LinkedList<>();
        for (int i = 1; i < list.size(); i++) {
            //下标从一开始,到最后一条记录时,将第一条记录插入
            T t = list.get(i);
            tempList.add(t);
            if (i == list.size() - 1) {
                //最后一条记录时,插入第一条记录
                tempList.add(list.get(0));
                List<T> tList = new LinkedList<>(tempList);
                lists.add(tList);
                tempList.clear();
            }
            if (i % size == 0) {
                //每size条记录算一组
                List<T> tList = new LinkedList<>(tempList);
                lists.add(tList);
                tempList.clear();
            }
        }

        return lists;
    }

    public List<List<T>> splitListByCount(List<T> list, int count) {
        List<List<T>> lists = new LinkedList<>();
        if (count <= 0) {
            throw new IllegalArgumentException("count应该大于0");
        } else if (count == 1) {
            lists.add(list);
            return lists;
        }
        int size = list.size() / count;
        for (int i = 0; i <= count; i++) {
            int start = i * size;
            int end = (i + 1) * size;
            List<T> tempList = new LinkedList<>();
            for (int j = start; j < end && j < list.size(); j++) {
                try {
                    tempList.add(list.get(j));
                }catch (ArrayIndexOutOfBoundsException e){
                    break;
                }
            }
            lists.add(tempList);
        }
        List<T> lastList = ((LinkedList<List<T>>) lists).removeLast();
        List<T> tempList = ((LinkedList<List<T>>) lists).getLast();
        tempList.addAll(lastList);

        return lists;
    }
}
